package main

import (
    "context"
    "flag"
    "fmt"
    "log"
    "net"
    "os"
    "os/signal"
    "syscall"

    "google.golang.org/grpc"
    "your_project/config"
    "your_project/data"
    "your_project/handlers"
    pb "your_project/proto"
    "your_project/world"
    "your_project/network" // 假设添加了network包
    "your_project/communication"
    pb "your_project/proto"
)

func main() {
    // 解析命令行参数
    serverType := flag.String("type", "world", "Server type: login, world, battle")
    port := flag.Int("port", 8080, "Server port")
    configFile := flag.String("config", "config.yaml", "Config file path")
    flag.Parse()

    // 加载配置
    if err := config.LoadConfig(*configFile); err != nil {
        log.Fatalf("Failed to load config: %v", err)
    }
    
    // 初始化etcd客户端
    err := server_management.InitEtcdClient([]string{"localhost:2379"})
    if err != nil {
        log.Fatalf("Failed to initialize etcd client: %v", err)
    }
    // 注册服务
    err = server_management.RegisterService("world_server", "localhost:8080")
    if err != nil {
        log.Fatalf("Failed to register service: %v", err)
    }
    // ..

    // 初始化数据库连接
    if err := data.InitDB(); err != nil {
        log.Fatalf("Failed to connect to database: %v", err)
    }
    defer data.CloseDB()

    // 创建gRPC服务器
    server := grpc.NewServer()

    // 创建消息处理器
    messageProcessor := network.NewMessageProcessor()

    // 根据服务器类型注册不同的服务
    switch *serverType {
    case "login":
        // 注册登录服务
        loginHandler := handlers.NewLoginHandler()
        pb.RegisterLoginServiceServer(server, loginHandler)
        log.Println("Login server initialized")

    case "world":
        // 注册世界服务
        worldHandler := handlers.NewWorldHandler()
        pb.RegisterWorldServiceServer(server, worldHandler)
        
        // 初始化世界管理器
        world.InitWorldManager()
        log.Println("World server initialized")

    case "battle":
        // 注册战斗服务
        battleHandler := handlers.NewBattleHandler()
        pb.RegisterBattleServiceServer(server, battleHandler)
        log.Println("Battle server initialized")

    case "social":
        // 注册社交服务
        socialHandler := handlers.NewSocialHandler()
        pb.RegisterSocialServiceServer(server, socialHandler)
        log.Println("Social server initialized")

    default:
        log.Fatalf("Unknown server type: %s", *serverType)
    }

    // 创建网络服务器
    networkServer := network.NewServer(*port, messageProcessor)

    // 启动服务器
    address := fmt.Sprintf(":%d", *port)
    lis, err := net.Listen("tcp", address)
    if err != nil {
        log.Fatalf("Failed to listen: %v", err)
    }

    log.Printf("Server started on port %d, type: %s", *port, *serverType)

    // 启动gRPC服务器
    go func() {
        if err := server.Serve(lis); err != nil {
            log.Fatalf("Failed to serve: %v", err)
        }
    }()

    // 启动网络服务器
    go func() {
        if err := networkServer.Start(); err != nil {
            log.Fatalf("Failed to start network server: %v", err)
        }
    }()

    // 等待中断信号优雅关闭服务器
    sigs := make(chan os.Signal, 1)
    signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

    <-sigs
    log.Println("Shutting down server...")

    // 优雅关闭服务器
    server.GracefulStop()
    networkServer.Stop()
    log.Println("Server shutdown complete")
}